//
//  TextInputViewController.swift
//  MovieApiTest
//
//  Created by linhan on 15/6/10.
//  Copyright (c) 2015年 linhan. All rights reserved.
//

import Foundation
import UIKit

class SWTextInputViewController: SWBaseViewController
{
    lazy private var _textView:UITextView = UITextView()
    
    var defaultText:String = ""
    
    var numberOfLines:Int = 1
    
    var index:Int = -1
    
    var completionCallback:((String, Int) -> Void)?
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        setup()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        _textView.becomeFirstResponder()
    }
    
    deinit
    {
        print("TextInputViewController DEINIT")
    }
    
    private func setup()
    {
        automaticallyAdjustsScrollViewInsets = false
        
        view.backgroundColor = UIColor(hex: 0xf5f5f5)
        
        let completeButton = createNavigationRightCustomButton("完成", image: nil, target: self, action: #selector(complete))
        completeButton.setTitleColor(UIColor(hex:0x4c4c4c), for: .normal)
        
        let cancelButton = createNavigationLeftCustomButton("取消", image: nil, target: self, action: #selector(cancel))
        cancelButton.setTitleColor(UIColor(hex:0x4c4c4c), for: .normal)
        
        
        let font = UIFont.systemFont(ofSize: 14)
        let lineHeight = font.lineHeight
        numberOfLines = max(numberOfLines, 1)
        let inset = _textView.textContainerInset
        let textViewHeight:CGFloat = CGFloat(numberOfLines) * lineHeight + inset.bottom + inset.top
        _textView.font = font
        _textView.frame = CGRectMake(0, navigationBarBottom + 15, view.width - 0, textViewHeight)
        _textView.backgroundColor = UIColor.white
        _textView.textColor = UIColor.black
        view.addSubview(_textView)
        
        _textView.text = defaultText
    }
    
    private func resign()
    {
        if _textView.isFirstResponder
        {
            _textView.resignFirstResponder()
        }
    }
    
    private func close()
    {
        if let _ = presentingViewController{
            dismiss(animated: true, completion: nil)
        }
        else{
            navigationController?.popViewController(animated: true)
        }
        
    }
    
    @objc private func cancel()
    {
        resign()
        close()
    }
    
    @objc private func complete()
    {
        resign()
        completionCallback?(_textView.text, index)
        close()
    }
    
    
    
}
